using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using System.Reflection;
using System;
namespace HotUpdate.Editor
{
    
    public partial class CreateNewHotUpdateScriptWindow : EditorWindow
    {
        [AttributeUsage(AttributeTargets.Method)]
        private class ScriptCreatorAttribute : Attribute
        {

        }
        [MenuItem("HotUpdateTool/创建脚本")]
        static void CreateWindow()
        {
            EditorWindow.GetWindow<CreateNewHotUpdateScriptWindow>(true, "创建脚本");
        }

        #region Private
        private string m_FileName;
        private List<KeyValuePair<string, Action<string>>> m_DrawMethods;
        private string[] m_DrawMethodNames;
        private string m_CurrentViewName;
        private SerializedObject m_SerializedObject;
        private string GetProjectFolder()
        {
            System.Type projectWindowUtilType = typeof(ProjectWindowUtil);
            MethodInfo getActiveFolderPath = projectWindowUtilType.GetMethod("GetActiveFolderPath", BindingFlags.Static | BindingFlags.NonPublic);
            object obj = getActiveFolderPath.Invoke(null, new object[0]);
            string pathToCurrentFolder = obj.ToString();
            return pathToCurrentFolder;
        }
        private void CreateNewTemplateScript(string templateName, string fileName, params KeyValuePair<string, string>[] replaces)
        {
            //加载模版
            var asset = Resources.Load<TextAsset>(templateName);
            var template = asset.text;
            //替换文本内容
            foreach (var p in replaces)
            {
                template = template.Replace(p.Key, p.Value);
            }
            //写入文件
            var dir = GetProjectFolder();
            if (!Directory.Exists(dir))
            {
                throw new System.Exception($"不存在路径{dir}");
            }
            FileStream fileStream = new FileStream(Path.Combine(dir, $"{fileName}.cs"), FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8);
            sw.Write(template);
            sw.Close();
            fileStream.Close();
            AssetDatabase.Refresh();
        }
        #endregion
        public CreateNewHotUpdateScriptWindow()
        {
            m_DrawMethods = new List<KeyValuePair<string, Action<string>>>();
            System.Type t = typeof(CreateNewHotUpdateScriptWindow);
            var ms = t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (var m in ms)
            {
                var attrs = m.GetCustomAttributes<ScriptCreatorAttribute>();
                foreach (var attr in attrs)
                {
                    try
                    {
                        Delegate d = Delegate.CreateDelegate(typeof(Action<string>), this, m);
                        var call =  d as Action<string>;
                        if (call != null)
                        {
                            m_DrawMethods.Add(new KeyValuePair<string, Action<string>>(m.Name,call));
                        }
                    }
                    catch(Exception e)
                    {
                        Debug.LogException(e);
                    }                                              
                }
            }
            m_DrawMethodNames = new string[m_DrawMethods.Count];
            for(int i=0;i<m_DrawMethods.Count;i++)
            {
                m_DrawMethodNames[i] = m_DrawMethods[i].Key;
            }
        }

        private void OnEnable()
        {
            m_SerializedObject = new SerializedObject(this);
        }



        private void OnGUI()
        {
            m_FileName = EditorGUILayout.TextField("脚本名称", m_FileName);
            int selectIndex = -1;
            for(int i=0;i<m_DrawMethodNames.Length;i++)
            {
                if (m_DrawMethodNames[i]==m_CurrentViewName)
                {
                    selectIndex = i;
                    break;
                }
            }
            selectIndex = EditorGUILayout.Popup("脚本类型",selectIndex, m_DrawMethodNames);
            if(selectIndex!=-1)
            {
                m_CurrentViewName = m_DrawMethodNames[selectIndex];
                m_DrawMethods[selectIndex].Value.Invoke(m_FileName);
            }
        }

        
    }
}

